<template>
  <div class="department-select">
    <!-- <div class="select-reference" @click="openDialog">
      <div class="select-content">
        <span v-if="selectedDepartments.length === 0" class="placeholder">{{ placeholder }}</span>
        <span v-else class="selected-text">{{ formatSelectedText }}</span>
      </div>
      <el-icon class="arrow-icon">
        <ArrowDown />
      </el-icon>
    </div> -->

    <el-dialog
      v-model="dialogVisible"
      title="选择部门"
      width="90%"
      class="department-select-dialog"
      append-to-body
      :before-close="handleDialogClose"
    >
      <div class="department-select-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb" v-if="breadcrumb.length > 0">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item 
              v-for="(item, index) in breadcrumb" 
              :key="item.id"
              @click="navigateToLevel(index)"
            >
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索部门"
            clearable
            prefix-icon="Search"
            size="small"
          />
        </div>

        <div class="selected-list">
          <div class="selected-title">
            <el-button-group>            
              <el-button class="clear-all-btn" @click="goToParentLevel" type="primary" link v-if="currentLevel > 0" title="返回上一级">返回上一级</el-button>
              <el-button class="clear-all-btn" @click="goToTopLevel" type="primary" link v-if="currentLevel > 0" title="返回顶层">顶层</el-button> 
            </el-button-group>            
          </div>
        </div>

        <div class="department-list" v-loading="loading">
          <!-- 全选按钮，仅在无限制模式下显示 -->
          <div class="select-all" v-if="selectedLimit === 0">
            <el-checkbox 
              :model-value="isAllSelected"
              @change="handleSelectAllChange"
            >
              全部选择
            </el-checkbox>
          </div>
          
          <div 
            v-for="dept in currentDepartments" 
            :key="dept.id" 
            class="department-item"
          >
            <div class="item-content" @click="handleDepartmentSelect(dept)">
              <el-icon class="dept-icon"><Folder /></el-icon>
              <div class="dept-info">
                <div class="dept-name">{{ dept.name }}</div>
               <!--  <div class="dept-count" v-if="dept.count">({{ dept.count }}人)</div> -->
              </div>
            </div>
            
            <div class="item-action">
              <!-- 如果有子部门，显示进入下级按钮 -->
              <el-button 
                v-if="dept.children && dept.children.length > 0" 
                link 
                type="primary" 
                @click="goToSubDepartment(dept)"
                class="sub-dept-btn"
              >
                下级
              </el-button>
              
              <!-- 使用复选框 -->
              <el-checkbox 
                :model-value="isSelected(dept)"
                :disabled="isCheckboxDisabled(dept)"
                @click.stop
                @change="(val) => handleCheckboxChange(val, dept)"
              />
            </div>
          </div>
          
          <div v-if="currentDepartments.length === 0 && !loading" class="no-data">
            暂无数据
          </div>
        </div>
        
        <!-- 限制提示 -->
        <div class="limit-tip" v-if="selectedLimit > 0 && selectedDepartments.length >= selectedLimit">
          最多只能选择 {{ selectedLimit }} 个部门
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">      
           <div v-if="selectedDepartments.length > 0">
            <el-text class="mx-1" type="primary" @click="selectedDialogVisible=true">已选择 ({{ selectedDepartments.length }})</el-text> 
          </div>
          
          <div class="footer-buttons">
            <el-button @click="clearSelection">清空</el-button>
            <el-button type="primary" @click="confirmSelection">确认</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="selectedDialogVisible"
      width="90%"
      class="department-select-dialog"
      :show-close="false"
    >
      <div class="selected-list">
          <div class="selected-title">
            已选择 ({{ selectedDepartments.length }})            
            <el-button 
              type="primary" 
              link 
              @click="clearAllSelected" 
              class="clear-all-btn"
            >
              清空
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="selectedDialogVisible=false" 
              class="clear-all-btn"
            >
              关闭
            </el-button>
          </div>
          <div class="selected-items">
            <el-tag
              v-for="(dept, index) in selectedDepartments"
              :key="dept.id"
              closable
              @close="removeSelected(dept, index)"
              class="selected-item-tag"
            >
              {{ dept.name }}
            </el-tag>
          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ArrowDown, Folder } from '@element-plus/icons-vue'

// 添加组件name以便在动态创建时能正确识别
defineOptions({
  name: 'DeptSelectorH5'
})

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: [Object, Array],
    default: () => null // [{ id: 1, name: '部门1' }]
  },
  selected:{
    type: Array,
    default: () => []
  },
  limit: {
    type: Number,
    default: 0 // 0表示无限制，其他值表示最多可选数量
  },
  placeholder: {
    type: String,
    default: '请选择部门'
  },
  departments: {
    type: Array,
    default: () => []
  },
  loadDepartments: {
    type: Function,
    default: null
  },
  dataApi: {
    type: String,
    default: ''
  },
  pageSize: {
    type: Number,
    default: 10
  },
  onConfirm:Function,
  onCancel: Function,
  visible: {
    type: Boolean,
    default: false
  },
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change', 'confirm','cancel'])

// 响应式数据
const dialogVisible = ref(props.visible)
const selectedDialogVisible = ref(false)
const loading = ref(false)
const searchKeyword = ref('')
const currentLevel = ref(0) // 当前层级
const breadcrumb = ref([]) // 面包屑导航

// 部门数据
const allDepartments = ref([])
const currentDepartments = ref([]) // 当前显示的部门

// 已选中的部门
const selectedDepartments = ref([])
const selectedLimit = ref(props.limit)
const currentCallback = ref(null)
// 格式化选中项显示文本
const formatSelectedText = computed(() => {
  if (selectedDepartments.value.length === 0) return ''
  if (selectedDepartments.value.length === 1) {
    return selectedDepartments.value[0].name
  }
  return `${selectedDepartments.value[0].name} 等${selectedDepartments.value.length}个部门`
})

// 计算是否全选
const isAllSelected = computed(() => {
  if (allDepartments.value.length === 0) return false
  
  // 获取所有部门（包括父部门和子部门）
  const getAllDepartments = (depts) => {
    let result = []
    depts.forEach(dept => {
      result.push(dept)
      if (dept.children && dept.children.length > 0) {
        result = result.concat(getAllDepartments(dept.children))
      }
    })
    return result
  }
  
  const allDepts = getAllDepartments(allDepartments.value)
  
  // 如果没有任何部门，返回false
  if (allDepts.length === 0) return false
  
  // 检查所有部门是否都被选中
  return allDepts.every(dept => isSelected(dept))
})

// 监听搜索关键词变化
watch(searchKeyword, (val) => {
  filterDepartments()
})

// 监听选中值变化
watch(() => props.modelValue, (val) => {
  if (val) {
    // 确保始终是数组格式
    if (Array.isArray(val)) {
      selectedDepartments.value = [...val]
    } else if (val) {
      // 如果是单个对象，转换为数组
      selectedDepartments.value = [val]
    } else {
      selectedDepartments.value = []
    }
  } else {
    selectedDepartments.value = []
  }
}, { immediate: true, deep: true })

// 判断是否选中
const isSelected = (dept) => {
  return selectedDepartments.value.some(item => item.id === dept.id)
}

// 判断复选框是否禁用
const isCheckboxDisabled = (dept) => {
  // 如果已达到选择上限且当前部门未被选中，则禁用
  return selectedLimit.value > 0 && 
         selectedDepartments.value.length >= selectedLimit.value && 
         !isSelected(dept)
}

// 处理全选变更
const handleSelectAllChange = (val) => {
  if (val) {
    // 全选所有部门（包括父部门和子部门）
    const getAllDepartments = (depts) => {
      let result = []
      depts.forEach(dept => {
        result.push(dept)
        if (dept.children && dept.children.length > 0) {
          result = result.concat(getAllDepartments(dept.children))
        }
      })
      return result
    }
    
    const allDepts = getAllDepartments(allDepartments.value)
    
    // 添加所有部门到已选列表中（避免重复添加）
    allDepts.forEach(dept => {
      if (!isSelected(dept)) {
        selectedDepartments.value.push(dept)
      }
    })
  } else {
    // 取消全选 - 清空所有已选部门
    selectedDepartments.value = []
  }
}

// 处理复选框变化
const handleCheckboxChange = (val, dept) => {
  if (val) {
    // 添加选中项
    if (!selectedDepartments.value.some(item => item.id === dept.id)) {
      // 检查是否超过限制
      if (selectedLimit.value === 0 || selectedDepartments.value.length < selectedLimit.value) {
        selectedDepartments.value.push(dept)
      }
    }
  } else {
    // 移除选中项
    const index = selectedDepartments.value.findIndex(item => item.id === dept.id)
    if (index !== -1) {
      selectedDepartments.value.splice(index, 1)
    }
  }
}

// 处理部门选择
const handleDepartmentSelect = (dept) => {
  // 如果有子部门，不处理选择事件，只处理导航
  if (dept.children && dept.children.length > 0) {
    return
  }
  
  // 直接切换选中状态
  const index = selectedDepartments.value.findIndex(item => item.id === dept.id)
  if (index !== -1) {
    // 已选中，移除
    selectedDepartments.value.splice(index, 1)
  } else {
    // 未选中，添加（检查限制）
    if (selectedLimit.value === 0 || selectedDepartments.value.length < selectedLimit.value) {
      selectedDepartments.value.push(dept)
    }
  }
}

// 进入子部门
const goToSubDepartment = (dept) => {
  if (!dept.children || dept.children.length === 0) return
  
  // 更新面包屑
  breadcrumb.value.push({
    id: dept.id,
    name: dept.name
  })
  
  // 更新当前层级和部门列表
  currentLevel.value++
  currentDepartments.value = dept.children
}

// 返回上一级
const goToParentLevel = () => {
  if (currentLevel.value <= 0) return
  
  // 更新面包屑
  breadcrumb.value.pop()
  
  // 更新层级
  currentLevel.value--
  
  // 根据当前层级更新部门列表
  if (currentLevel.value === 0) {
    currentDepartments.value = allDepartments.value
  } else {
    // 查找当前层级的父级部门
    let targetDepts = allDepartments.value
    for (let i = 0; i < currentLevel.value; i++) {
      const parentId = breadcrumb.value[i].id
      const parentDept = targetDepts.find(dept => dept.id === parentId)
      if (parentDept && parentDept.children) {
        targetDepts = parentDept.children
      }
    }
    currentDepartments.value = targetDepts
  }
}

// 返回顶层
const goToTopLevel = () => {
  currentLevel.value = 0
  breadcrumb.value = []
  currentDepartments.value = allDepartments.value
}

// 导航到指定层级
const navigateToLevel = (index) => {
  // 如果点击的是当前层级，不处理
  if (index === breadcrumb.value.length) return
  
  // 截断面包屑到指定层级
  breadcrumb.value = breadcrumb.value.slice(0, index)
  
  // 更新层级
  currentLevel.value = index
  
  // 更新部门列表
  if (index === 0) {
    currentDepartments.value = allDepartments.value
  } else {
    // 查找指定层级的部门
    let targetDepts = allDepartments.value
    for (let i = 0; i < index; i++) {
      const parentId = breadcrumb.value[i].id
      const parentDept = targetDepts.find(dept => dept.id === parentId)
      if (parentDept && parentDept.children) {
        targetDepts = parentDept.children
      }
    }
    currentDepartments.value = targetDepts
  }
}

// 移除已选部门
const removeSelected = (dept, index) => {
  selectedDepartments.value.splice(index, 1)
}

// 一键清空所有已选部门
const clearAllSelected = () => {
  selectedDepartments.value = []
}

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true
  // 重置到顶层
  goToTopLevel()
}

// 处理对话框关闭
const handleDialogClose = (done) => {
  if (props.onCancel && typeof props.onCancel === 'function') {
    props.onCancel()
  }
  emit('cancel')
  done()
}

// 确认选择
const confirmSelection = () => {
  // 根据limit值决定返回的数据格式
  if (selectedLimit.value === 1) {
    // 单选模式，返回第一个选中的部门或null
    const selected = selectedDepartments.value.length > 0 ? selectedDepartments.value[0] : null
    emit('update:modelValue', selected)
    emit('change', selected)
  } else {
    // 多选模式，返回选中的部门数组
    emit('update:modelValue', [...selectedDepartments.value])
    emit('change', [...selectedDepartments.value])    
  }

  const result = {
    ids: [...selectedDepartments.value].map(dept => dept.id),
    names: [...selectedDepartments.value].map(dept => dept.name)
  }

  if (props.onConfirm && typeof props.onConfirm === 'function') {
    try {
      props.onConfirm(result)
    } catch (error) {
      console.error('onConfirm 回调执行出错:', error)
    }
  }
  emit('confirm', result)
  if (currentCallback.value) {
    currentCallback.value(result)
  }
  dialogVisible.value = false
}

// 清空选择
const clearSelection = () => {
  selectedDepartments.value = []
}

// 过滤部门
const filterDepartments = () => {
  // 搜索功能可以在此实现
  if (searchKeyword.value) {
    // 简单实现搜索功能
    const keyword = searchKeyword.value.toLowerCase()
    const searchResults = []
    
    // 递归搜索所有部门
    const searchInDepartments = (depts) => {
      depts.forEach(dept => {
        if (dept.name.toLowerCase().includes(keyword)) {
          searchResults.push(dept)
        }
        if (dept.children && dept.children.length > 0) {
          searchInDepartments(dept.children)
        }
      })
    }
    
    searchInDepartments(allDepartments.value)
    currentDepartments.value = searchResults
  } else {
    // 如果没有搜索关键词，显示当前层级的部门
    if (currentLevel.value === 0) {
      currentDepartments.value = allDepartments.value
    } else {
      // 查找当前层级的部门
      let targetDepts = allDepartments.value
      for (let i = 0; i < currentLevel.value; i++) {
        const parentId = breadcrumb.value[i].id
        const parentDept = targetDepts.find(dept => dept.id === parentId)
        if (parentDept && parentDept.children) {
          targetDepts = parentDept.children
        }
      }
      currentDepartments.value = targetDepts
    }
  }
}

// 加载部门数据
const loadDepartmentData = async () => {
  loading.value = true
  try {
    if(props.dataApi){
        const response = await fetch(props.dataApi)
        const data = await response.json()
        allDepartments.value = data || [];
    }else if (props.loadDepartments) {
      allDepartments.value = await props.loadDepartments()
    } else if (props.departments && props.departments.length > 0) {
      allDepartments.value = [...props.departments]
    } else {
      // 模拟数据
      allDepartments.value = [
        {
          id: 1,
          name: '管理部门',
          count: 25,
          children: [
            {
              id: 11,
              name: '人力资源部',
              count: 10,
              children: [
                {
                  id: 111,
                  name: '招聘组',
                  count: 5
                },
                {
                  id: 112,
                  name: '培训组',
                  count: 5
                }
              ]
            },
            {
              id: 12,
              name: '财务部',
              count: 8
            },
            {
              id: 13,
              name: '行政部',
              count: 7
            }
          ]
        },
        {
          id: 2,
          name: '技术部门',
          count: 45,
          children: [
            {
              id: 21,
              name: '前端开发部',
              count: 15,
              children: [
                {
                  id: 211,
                  name: 'Vue组',
                  count: 8
                },
                {
                  id: 212,
                  name: 'React组',
                  count: 7
                }
              ]
            },
            {
              id: 22,
              name: '后端开发部',
              count: 20
            },
            {
              id: 23,
              name: '测试部',
              count: 10
            }
          ]
        },
        {
          id: 3,
          name: '销售部门',
          count: 30,
          children: [
            {
              id: 31,
              name: '国内销售部',
              count: 20
            },
            {
              id: 32,
              name: '国际销售部',
              count: 10
            }
          ]
        }
      ]
    }
    
    // 初始化显示顶层部门
    currentDepartments.value = allDepartments.value
    
    // 初始化过滤
    filterDepartments()
  } catch (error) {
    console.error('加载部门数据失败:', error)
  } finally {
    loading.value = false
  }
}
// 根据部门ID查找部门
const findDepartmentById = (departments, id) => {
  for (const dept of departments) {
    if (dept.id === id) {
      return dept;
    }
    if (dept.children && dept.children.length > 0) {
      const found = findDepartmentById(dept.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};
/**
 * 根据选中的部门ID转换成部门
 * @param selectedIds 选中的部门ID
 */
const selectedIdsToDepartments = (selectedIds = []) => {
  if(selectedLimit.value >= 1){
    selectedIds = selectedIds.slice(0, selectedLimit.value)
  }
  selectedDepartments.value = [];
  nextTick(() => {
    selectedIds.map(id => {
      const dept = findDepartmentById(allDepartments.value, id)
      if (dept) {
        selectedDepartments.value.push(dept)
      }
    })
  })
}

const selectDeptH5 = (selectedIds = [], callback, limitCount = 0) => {
  currentCallback.value = callback
  selectedLimit.value = limitCount
  //loadDepartmentData()
  openDialog()

  selectedIdsToDepartments(selectedIds)    
}

// 组件挂载时加载数据
onMounted(() => {
  loadDepartmentData()

  if (props.selected) {
    if (Array.isArray(props.selected)) {
      selectedIdsToDepartments(props.selected)
      return
    }
    selectedIdsToDepartments(props.selected.split(','))
  }
})

defineExpose({
  selectDeptH5,
  selectDept: selectDeptH5
})
</script>

<style scoped lang="scss">
.department-select {
  width: 100%;
}

.select-reference {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  min-height: 32px;

  &:hover {
    border-color: #c0c4cc;
  }

  .select-content {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .placeholder {
    color: #c0c4cc;
  }

  .selected-text {
    color: #606266;
  }

  .arrow-icon {
    color: #c0c4cc;
    transition: transform 0.3s;
  }
}

.department-select-dialog {
  border-radius: 8px;
  overflow: hidden;
  
  .department-select-content {
    .breadcrumb {
      padding: 10px 0;
      border-bottom: 1px solid #eee;
      margin-bottom: 10px;
    }

    .search-box {
      padding: 12px 0;
      margin-bottom: 10px;
    }

    .department-list {
      max-height: 300px;
      overflow-y: auto;
      
      .select-all {
        padding: 8px 16px;
        border-bottom: 1px solid #f5f5f5;
        background-color: #f9f9f9;
      }
      
      .department-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        border-bottom: 1px solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        .item-content {
          display: flex;
          align-items: center;
          flex: 1;
          cursor: pointer;
          
          .dept-icon {
            color: #409eff;
            margin-right: 10px;
            font-size: 18px;
          }
          
          .dept-info {
            display: flex;
            align-items: baseline;
            
            .dept-name {
              font-size: 14px;
              color: #333;
            }
            
            .dept-count {
              margin-left: 5px;
              font-size: 12px;
              color: #999;
            }
          }
        }
        
        .item-action {
          display: flex;
          align-items: center;
          
          .sub-dept-btn {
            margin-right: 10px;
          }
        }
      }
    }

    .no-data {
      text-align: center;
      padding: 20px;
      color: #999;
    }
    
    .limit-tip {
      margin-top: 10px;
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
      font-size: 12px;
      color: #999;
      text-align: center;
    }
  }

  .selected-list {
      margin-bottom: 15px;
      
      .selected-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .clear-all-btn {
          font-size: 14px;
        }
      }
      
      .selected-items {
        .selected-item-tag {
          margin-right: 8px;
          margin-bottom: 8px;
        }
      }
    }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }
  .footer-buttons {
    margin-left: auto;
  }
}
</style>